package bpmn.controller;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/file")
public class TestController {

    private static final String RESOURCE_DIR = "E:\\work\\demo\\camunda-demo\\src\\main\\resources\\";

    @GetMapping("/test")
    public Map<String,Object> test(){
        MapBuilder<String, Object> builder = MapUtil.builder();
        builder.put("asdfasd","sdfasdfasd");
        return builder.build();

    }

    @GetMapping("/list")
    public List<String> files() {
        File file = new File(RESOURCE_DIR);
        File[] files = file.listFiles();
        ArrayList<String> list = new ArrayList<>();
        for (File f : files) {
            String fileName = f.getName();
            Matcher matcher = Pattern.compile("\\.bpmn$").matcher(fileName);
            if (matcher.find()) {
                list.add(fileName);
            }
        }
        return list;
    }

    @GetMapping("/get")
    public void getFile(HttpServletResponse response, String name) throws IOException {
        response.setContentType("application/xml;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        InputStream fileInputStream = new FileInputStream(new File(RESOURCE_DIR + name));
        byte[] buf = new byte[2048];
        int len;
        while (-1 != (len = fileInputStream.read(buf))) {
            outputStream.write(buf, 0, len);
        }
    }

    @PostMapping("/save")
    public void saveFile(@RequestBody Map<String, Object> map) throws Exception {
        String key = (String) map.get("file");
        if(StrUtil.isBlank(key)){
            throw new Exception("文件名不能为空");
        }
        if (!Pattern.compile("\\.bpmn").matcher(key).find()) {
            key = key + ".bpmn";
        }
        String fileName = RESOURCE_DIR + key;
        File file = new File(fileName);
        if (file.exists()) {
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(fileName, false);
        fileWriter.flush();
        fileWriter.write((String) map.get("content"));
        fileWriter.close();
    }

}
